package com.ruoyi.web.controller.system;

import com.ruoyi.WebSocketTemplate;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.ExcelUtil2;
import com.ruoyi.system.util.ExcelUtil2Element;
import com.ruoyi.system.util.WorkbookExportUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 菜房订单 信息操作处理
 *
 * @author ruoyi
 * @date 2019-08-29
 */
@Controller
@RequestMapping("/system/ncOrderCf")
public class NcOrderCfController extends BaseController {
    private String prefix = "system/ncOrderCf";
    private String caifangOrder = "system/screen";

    @Autowired
    private INcOrderCfService ncOrderCfService;
    @Autowired
    private INcCaiService caiService;
    @Autowired
    private INcOutputChickenService chickenService;

    @Autowired
    private INcPlanService planService;

    @Autowired
    private ISysNoticeService noticeService;

    @Autowired
    private WebSocketTemplate socketTemplate;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ISysDeptService deptService;

    @RequiresPermissions("system:ncOrderCf:view")
    @GetMapping()
    public String ncOrderCf(String status, ModelMap mmap) {
        mmap.put("status", status);
        return prefix + "/ncOrderCf";
    }

    /*待执行但尚未出库的订单*/
    @GetMapping("ncOrderCf-ordered")
    public String ordered(String status, Integer type, ModelMap mmap) {
        mmap.put("status", status);
        mmap.put("type", type);
        return prefix + "/ncOrderCf-ordered";
    }

    /**
     * 查询菜房订单列表
     */
    @RequiresPermissions("system:ncOrderCf:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcOrderCf ncOrderCf) {
        startPage();
        List<NcOrderCf> list = ncOrderCfService.selectNcOrderCfList(ncOrderCf);
        return getDataTable(list);
    }

    /**
     * 查询菜房订单列表
     */
    @RequiresPermissions("system:ncOrderCf:list")
    @PostMapping("/listTodays")
    @ResponseBody
    public TableDataInfo listTodays(NcOrderCf ncOrderCf) {
        List<NcOrderCf> list = ncOrderCfService.selectNcOrderCfList(ncOrderCf);
        for (int i = 0; i < list.size(); i++) {
            NcOrderCf o = list.get(i);
            if ("5".equals(o.getCforderStatus()) && NcUtils.differentDaysByDate(new Date(), o.getFinishTime()) >= 1) {
                list.remove(o);
                i--;
            }
        }
        return getDataTable(list);
    }


    /**
     * 导出菜房订单列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcOrderCf ncOrderCf) {
        List<NcOrderCf> list = ncOrderCfService.selectNcOrderCfList(ncOrderCf);
        ExcelUtil2<NcOrderCf> util = new ExcelUtil2<NcOrderCf>(NcOrderCf.class);
        return util.exportExcel(list, "菜房订单列表");
    }

    /**
     * 新增菜房订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存菜房订单
     */
    @RequiresPermissions("system:ncOrderCf:add")
    @Log(title = "菜房订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(NcOrderCf ncOrderCf) {
        ncOrderCf.setCforderCode(NcUtils.getOrderCode());
        ncOrderCf.setCreateTime(new Date());
        ncOrderCf.setCreateBy(ShiroUtils.getLoginName());

        if (1 == ncOrderCf.getCforderType()) {
            ncOrderCf.setCforderFor(1);
        } else {
            ncOrderCf.setCforderFor(2);
        }

        ncOrderCf = ncOrderCfService.fillValues(ncOrderCf);
        if (ncOrderCf == null) {
            return AjaxResult.error("未找到此品种");
        }
        //如果是鸡蛋或者牛奶则，设置订单的cforderStatus 为 待牛舍确认、或待鸡舍确认
        NcCai ncCai = caiService.selectCaiById(ncOrderCf.getCropVarieties());
        if (ncCai.getCode().startsWith("milk")) {
            ncOrderCf.setCforderStatus("6");//牛舍待确认
        } else if (ncCai.getCode().startsWith("chicken")) {
            ncOrderCf.setCforderStatus("7");//鸡舍待确认
        }


        return toAjax(ncOrderCfService.insertNcOrderCf(ncOrderCf));
    }

    /**
     * 修改菜房订单
     */
    @GetMapping("/edit/{cforderId}")
    public String edit(@PathVariable("cforderId") Long cforderId, ModelMap mmap) {
        NcOrderCf ncOrderCf = ncOrderCfService.selectNcOrderCfById(cforderId);
        mmap.put("ncOrderCf", ncOrderCf);
        return prefix + "/edit";
    }

    /**
     * 对于鸡舍菜房确认
     */
    @GetMapping("/confirm/{cforderId}")
    public String confirm(@PathVariable("cforderId") Long cforderId, ModelMap mmap) {
        NcOrderCf ncOrderCf = ncOrderCfService.selectNcOrderCfById(cforderId);
        mmap.put("ncOrderCf", ncOrderCf);

        return prefix + "/confirm";
    }

    /**
     * 对于鸡舍菜房确认
     */
    @PostMapping("/confirmCow")
    @ResponseBody
    public AjaxResult confirmCow(NcOrderCf ncOrderCf) {
        ncOrderCf.setCforderStatus("5");//已完成
        ncOrderCf.setFinishTime(new Date());
        return AjaxResult.success(ncOrderCfService.updateNcOrderCf(ncOrderCf));
    }

    /**
     * 对于牛舍 菜房确认
     */
    @PostMapping("/confirm")
    @ResponseBody
    public AjaxResult confirmSave(NcOrderCf ncOrderCf) {
        ncOrderCf.setCforderStatus("5");//已完成
        ncOrderCf.setFinishTime(new Date());
//        更新 鸡舍出库表
        NcOutputChicken o = new NcOutputChicken();
        o.setCforderId(ncOrderCf.getCforderId());
        List<NcOutputChicken> chickens = chickenService.selectNcOutputChickenList(o);
        if (chickens.size() > 0) {
            o = chickens.get(0);
            o.setOutputWeight(ncOrderCf.getOutputWeight());
            chickenService.updateNcOutputChicken(o);
        }
        return AjaxResult.success(ncOrderCfService.updateNcOrderCf(ncOrderCf));
    }

    /**
     * 修改保存菜房订单
     */
    @RequiresPermissions("system:ncOrderCf:edit")
    @Log(title = "菜房订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(NcOrderCf ncOrderCf) {
        if (ncOrderCf.getCforderType() != null) {
            if (ncOrderCf.getCforderType() != null && ncOrderCf.getCforderType() > 0) {

                if (1 == ncOrderCf.getCforderType()) {
                    ncOrderCf.setCforderFor(1);
                } else {
                    ncOrderCf.setCforderFor(2);
                }
            }
        }
        ncOrderCf = ncOrderCfService.fillValues(ncOrderCf);
        if (ncOrderCf == null) {
            return AjaxResult.error("未找到此品种");
        }
        return toAjax(ncOrderCfService.updateNcOrderCf(ncOrderCf));
    }

    /**
     * 修改保存菜房订单
     */
    @RequiresPermissions("system:ncOrderCf:edit")
    @Log(title = "菜房订单", businessType = BusinessType.UPDATE)
    @PostMapping("/distribution")
    @ResponseBody
    public AjaxResult distribution(NcOrderCf ncOrderCf) {
        String userId = "";
        int i = ncOrderCfService.updateNcOrderCf(ncOrderCf);

        NcOrderCf ncOrderCf1 = ncOrderCfService.selectNcOrderCfById(ncOrderCf.getCforderId());


        //判断分配类型
        String distribution = ncOrderCf.getDistribution();
        //分配检测 发送工作通知
        if ("1".equals(distribution)) {
            SysNotice notice = new SysNotice();
            notice.setNoticeTitle("检测任务");
            notice.setNoticeType("3");
            notice.setStatus("0");
            notice.setNoticeContent("订单编号【" + ncOrderCf1.getCforderCode() + "】     " + ncOrderCf1.getCropNameCn() + "     " + ncOrderCf1.getCropVarietiesCn() + "     " + ncOrderCf1.getRequestAmount() + "（kg）");
            notice.setCreateBy(ShiroUtils.getLoginName());
            notice.setCreateTime(new Date());
            notice.setReadType(2); //设置未读
            notice.setDeptId("2"); //设置选择用户


            //订单品种id
            Long cropVarieties = ncOrderCf.getCropVarieties();
            NcCai cai = new NcCai();
            cai.setCaiId(cropVarieties);
            List<NcCai> ncCais = caiService.selectCaiList(cai);

            String code = ncCais.get(0).getCode();


            //设置用户id 1 检测 2温室
            SysUser user = new SysUser();
            List<SysUser> users = new ArrayList<>();

            //检测部门
            user.setDeptId(Long.parseLong("248"));
            List<SysUser> sysUsers1 = sysUserService.selectUserList(user);
            users.addAll(sysUsers1);


            if (users != null && users.size() > 0) {
                for (SysUser sysUser : users) {
                    userId += sysUser.getUserId() + ",";
                }
            }
            notice.setUserId(userId);
            if (noticeService.insertNotice(notice) > 0) {
                socketTemplate.sendMessage(notice);
            }


            //温室部门
            users = new ArrayList<>();
            notice.setNoticeTitle("采摘任务");
            //根据订单找到计划id
            Integer planId = ncOrderCfService.selectNcOrderCfById(ncOrderCf.getCforderId()).getPlanId();
            if (planId != null) {
                //订单对应计划
                NcPlan ncPlan = planService.selectNcPlanById(Long.parseLong(planId + ""));
                //获取订单对应计划的班组
                String team = ncPlan.getTeam();
                if (team != null) {
                    user = new SysUser();
                    user.setDeptId(Long.parseLong(team));
                    List<SysUser> sysUsers = sysUserService.selectUserList(user);
                    users.addAll(sysUsers);
                } else {
                    List<SysUser> sysUsers = sysUserService.selectUserList(new SysUser());
                    sysUsers.removeIf(thisUser -> !deptService.selectDeptById(thisUser.getDeptId()).getAncestors().contains("100"));
                    users.addAll(sysUsers);
                }
            }

            if (users != null && users.size() > 0) {
                for (SysUser sysUser : users) {
                    userId += sysUser.getUserId() + ",";
                }
            }
            notice.setUserId(userId);
            if (noticeService.insertNotice(notice) > 0) {
                socketTemplate.sendMessage(notice);
            }
        }

        return toAjax(i);
    }

    /**
     * 删除菜房订单
     */
    @RequiresPermissions("system:ncOrderCf:remove")
    @Log(title = "菜房订单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncOrderCfService.deleteNcOrderCfByIds(ids));
    }


    /**
     * 确认生成订单记录单
     */
    @Log(title = "确认生成订单记录单", businessType = BusinessType.DELETE)
    @PostMapping("/confirmTable")
    @ResponseBody
    public AjaxResult confirmTable(String ids) {
        SysUser user = null;
        SysNotice notice = null;
        if (!"".equals(ids)) {
            //订单主键字符串
            String[] split = ids.split(",");

            for (String cfOrderId : split) {
                //查询订单
                NcOrderCf orderCf = ncOrderCfService.selectNcOrderCfById(Long.parseLong(cfOrderId));

                // 根据订单需求 判断订单类型
                Long cropVarieties = orderCf.getCropVarieties();

                NcCai cai = caiService.selectCaiById(cropVarieties);
                String code = cai.getCode();
                notice = new SysNotice();
                notice.setNoticeType("3");
                notice.setReadType(2); //设置未读
                notice.setStatus("0");
                notice.setDeptId("2"); //设置选择用户
                notice.setCreateTime(new Date());
                notice.setCreateBy(ShiroUtils.getLoginName());
                if (code.contains("chicken")) {
                    notice.setNoticeTitle("鸡肉订单");
                    notice.setNoticeContent("订单编号【" + orderCf.getCforderCode() + "】" + orderCf.getCropNameCn() + "" + orderCf.getCropVarietiesCn());

                    user = new SysUser();
                    user.setDeptId(249L);
                    List<SysUser> users = sysUserService.selectUserList(user);

                    String userId = "";
                    if (users != null && users.size() > 0) {
                        for (SysUser sysUser : users) {
                            userId += sysUser.getUserId() + ",";
                        }
                    }
                    notice.setUserId(userId);

                    int no = noticeService.insertNotice(notice);
                    if (no > 0) {
                        socketTemplate.sendMessage(notice);
                    }
                } else if (code.contains("milk")) {

                    //牛舍订单
                    notice.setNoticeTitle("牛奶订单");
                    notice.setNoticeContent( "订单编号【" + orderCf.getCforderCode() + "】" + orderCf.getCropNameCn() + "" + orderCf.getCropVarietiesCn());

                    user = new SysUser();
                    user.setDeptId(211L);
                    List<SysUser> users = sysUserService.selectUserList(user);

                    String userId = "";
                    if (users != null && users.size() > 0) {
                        for (SysUser sysUser : users) {
                            userId += sysUser.getUserId() + ",";
                        }
                    }
                    notice.setUserId(userId);

                    int no = noticeService.insertNotice(notice);
                    if (no > 0) {
                        socketTemplate.sendMessage(notice);
                    }
                } /*else {
                    //温室部门
                    notice.setNoticeTitle("温室订单");
                    notice.setNoticeContent("新增" + "【" + orderCf.getCforderCode() + "】" + orderCf.getCropNameCn() + "" + orderCf.getCropVarietiesCn());

                    //根据订单找到计划id
                    Integer planId = orderCf.getPlanId();
                    List<SysUser> users = sysUserService.selectUserList(user);

                    if (planId != null) {
                        //订单对应计划
                        NcPlan ncPlan = planService.selectNcPlanById(Long.parseLong(planId + ""));
                        //获取订单对应计划的班组
                        String team = ncPlan.getTeam();

                        if (team != null) {
                            user = new SysUser();
                            user.setDeptId(Long.parseLong(team));
                            List<SysUser> sysUsers = sysUserService.selectUserList(user);
                            users.addAll(sysUsers);
                        } else {
                            List<SysUser> sysUsers = sysUserService.selectUserList(new SysUser());
                            sysUsers.removeIf(thisUser -> !deptService.selectDeptById(thisUser.getDeptId()).getAncestors().contains("100"));
                            users.addAll(sysUsers);
                        }


                    }

                    String userId = "";
                    if (users != null && users.size() > 0) {
                        for (SysUser sysUser : users) {
                            userId += sysUser.getUserId() + ",";
                        }
                    }
                    notice.setUserId(userId);

                    int no = noticeService.insertNotice(notice);
                    if (no > 0) {
                        socketTemplate.sendMessage(notice);
                    }


                }*/

            }
        }
        return toAjax(ncOrderCfService.createNcOrderCfByIds(ids, ShiroUtils.getSysUser()));
    }

    /**
     * 修改订单所匹配的计划
     */
    @GetMapping("/editOrderPlan/{cforderId}")
    public String editStandard(@PathVariable("cforderId") Long cforderId, ModelMap mmap) {

        //校验
        NcOrderCf order = ncOrderCfService.selectNcOrderCfById(cforderId);

        NcPlan plan = new NcPlan();
        plan.setCropVarieties(order.getCropVarieties());
        plan.setPlanType(order.getCforderFor());
        List<NcPlan> plans = planService.selectNcPlanList(plan);

        for (NcPlan p : plans) {
            if ((p.getPlanId() + "").equals("" + order.getPlanId())) {
                p.setFlag(true);
                break;
            }
        }
        mmap.put("plans", plans);
        mmap.put("cforderId", cforderId);
        mmap.put("cforder", order);

        return prefix + "/edit-order-plan";
    }

    /**
     * 修改订单所匹配的计划
     */
    @Log(title = "修改订单所匹配的计划", businessType = BusinessType.UPDATE)
    @PostMapping("/editOrderPlan")
    @ResponseBody
    public AjaxResult editOrderPlanSave(NcOrderCf ncOrderCf) {
        if (ncOrderCf.getPlanId() != null && ncOrderCf.getPlanId() > 0) {
            ncOrderCf.setHasPlan("1");
        }
        return toAjax(ncOrderCfService.updateNcOrderCf(ncOrderCf));
    }


    @Log(title = "菜房订单导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<NcOrderCf> util = new ExcelUtil<NcOrderCf>(NcOrderCf.class);
        List<NcOrderCf> userList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = ncOrderCfService.importOrder(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        WorkbookExportUtil wu = new WorkbookExportUtil(new XSSFWorkbook(), "订单数据模板");
        /*订单模板*/
        ExcelUtil2Element<NcOrderCf> m_order = new ExcelUtil2Element<>(NcOrderCf.class, wu);
        m_order.importTemplateExcel("订单数据模板");

        /*菜分类基础数据*/
        List<NcCai> cais = caiService.selectCaiListHasParent2(new NcCai());
        for (int i = 0; i < cais.size(); i++) {
            NcCai c = cais.get(i);
            String a = c.getAncestors();
            if (a.split(",").length != 3) {
                cais.remove(i);
                i--;
            }
        }
        ExcelUtil2Element<NcCai> m_cai = new ExcelUtil2Element<>(NcCai.class, wu);
        m_cai.exportExcel(cais, "菜分类基础数据");
        /*订单类型基础数据 cforderType*/
        List<SysDictData> types = dictDataService.selectDictDataByType("cforderType");
        ExcelUtil2Element<SysDictData> m_type = new ExcelUtil2Element<>(SysDictData.class, wu);
        m_type.exportExcel(types, "订单类型基础数据");

        /*需求数量字典 normal_unit*/
        List<SysDictData> units = dictDataService.selectDictDataByType("normal_unit");
        ExcelUtil2Element<SysDictData> m_dict = new ExcelUtil2Element<>(SysDictData.class, wu);
        m_dict.exportExcel(units, "单位基础数据");
        return wu.exportExcel();

    }

    @GetMapping("/caifang/order/{id}")
    public String ncOrderCf(String status, ModelMap mmap, @PathVariable(name = "id") Integer id) {
        mmap.put("id", id);
        return caifangOrder + "/caifangOrder";
    }

    /**
     * 当天大屏蔬菜整理间1 2的订单
     */
    @PostMapping("/todayList/{id}")
    @ResponseBody
    public TableDataInfo todayList(NcOrderCf ncOrderCf, @PathVariable(name = "id") String id) {
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String today = format2.format(Calendar.getInstance().getTime());
        ncOrderCf.getParams().put("listToDay", today);
        ncOrderCf.setCforderStatus(String.valueOf(4));
        ncOrderCf.setStatus("2");
        ncOrderCf.setIsCheck(2);
        ncOrderCf.setCforderFor(Integer.valueOf(id));
        startPage();
        List<NcOrderCf> list = ncOrderCfService.selectNcOrderCfList(ncOrderCf);
        if (list == null || list.size() == 0) {
            list = new ArrayList<NcOrderCf>();
        }
        return getDataTable(list);
    }


}
